package com.stockz.equity.charting.util;

public class MathUtil {

	public static int fitY(int top, int bottom,
			double min, double max, double value, boolean log){
		if(value == Double.MAX_VALUE){
			return Integer.MAX_VALUE;
		}else if(value == Double.MIN_VALUE){
			return Integer.MIN_VALUE;
		}
		
		if(log){
			min = Math.log(min);
			max = Math.log(max);
			value = Math.log(value);
		}
		return (int)(bottom - ((bottom-top)*(value-min)/(max-min)));
	}
	
	public static double unfitY(int top,int bottom,
			double min, double max,int value,boolean log){
		if(value == Integer.MAX_VALUE){
			return Double.MAX_VALUE;
		}else if(value == Integer.MIN_VALUE){
			return Double.MIN_VALUE;
		}
		
		double b = 0,t = 0, v= 0;
		
		if(log){
			b = Math.log(bottom);
			t = Math.log(top);
			v = Math.log(value+10);
			return min + (b-v)*(max-min)/(b-t);
		}else{
			return min + (bottom-value)*(max-min)/(bottom-top);
		}
	}
	
	public static int fitX(int min,int hConst,int endIndex,int index){
		if(index == Integer.MAX_VALUE){
			return Integer.MAX_VALUE;
		}else if(index == Integer.MIN_VALUE){
			return Integer.MIN_VALUE;
		}
		return  min + hConst*(endIndex-1-index) + hConst/2;
	}
	
	public static int unfitX(int min,int hConst, int endIndex, int x){
		if(x == Integer.MAX_VALUE){
			return Integer.MAX_VALUE;
		}else if(x == Integer.MIN_VALUE){
			return Integer.MIN_VALUE;
		}
		return endIndex -1 - (x - min - (hConst/2))/hConst;
	}
	
	public static double max(double[] values,int start, int end){
		double max = Double.MIN_VALUE;
		if(values != null && values.length != 0 && start >=0 && end >=start && end <= values.length){
			for(int i = start; i < end; i++){
				if(max < values[i]){
					max = values[i];
				}
			}
		}else{
			max = 0;
		}
		return max;
	}
	
	
	public static double min(double[] values,int start, int end){
		double min = Double.MAX_VALUE;
		if(values != null && values.length != 0 && start >=0 && end >=start && end <= values.length){
			for(int i = start; i < end; i++){
				if(min > values[i]){
					min = values[i];
				}
			}
		}else{
			min = 0;
		}
		return min;
	}
}
